package com.zhuizikejithreeig.cn.fragment;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.inuker.bluetooth.library.BluetoothClient;
import com.inuker.bluetooth.library.beacon.Beacon;
import com.inuker.bluetooth.library.connect.listener.BleConnectStatusListener;
import com.inuker.bluetooth.library.connect.response.BleConnectResponse;
import com.inuker.bluetooth.library.connect.response.BleReadResponse;
import com.inuker.bluetooth.library.connect.response.BleWriteResponse;
import com.inuker.bluetooth.library.model.BleGattProfile;
import com.inuker.bluetooth.library.search.SearchRequest;
import com.inuker.bluetooth.library.search.SearchResult;
import com.inuker.bluetooth.library.search.response.SearchResponse;
import com.inuker.bluetooth.library.utils.BluetoothLog;
import com.zhuizikejithreeig.cn.content.ContectUtils;
import com.zhuizikejithreeig.cn.threeigkeji.CompontApplayCation;
import com.zhuizikejithreeig.cn.threeigkeji.R;
import com.zhuizikejithreeig.cn.threeigkeji.loginfo.BundingSetActivity;
import com.zhuizikejithreeig.cn.threeigkeji.loginfo.LoginActivity;
import com.zhuizikejithreeig.cn.threeigkeji.loginfo.SaoMaActivity;
import com.zhuizikejithreeig.cn.utils.ToastMake;
import com.zhuizikejithreeig.cn.utils.Utils;
import java.util.UUID;
import static com.inuker.bluetooth.library.Code.REQUEST_SUCCESS;
public class SimpleCardFragment extends Fragment implements View.OnClickListener {
    private String mTitle;
    private ImageView mImageView;
    private TextView mTextButton;
    private LinearLayout mLinearLayout;
    private String uri;
    private String mac;
    private Button mProgressBar;
    private TextView handtext;
    private TextView foottext;
    private String mPhone;
    private TextView mModleButton;
    private TextView mStringButton;
    private static final UUID serviceUUID = UUID.fromString("00005550-0000-1000-8000-00805F9B34FB");
    private static final UUID characterUUID = UUID.fromString("00005556-0000-1000-8000-00805F9B34FB");
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothClient mClient ;


    //这是单例模式,懒汉式
    public static SimpleCardFragment getInstance(String title, String uri, String mac) {
        SimpleCardFragment sf = new SimpleCardFragment();
        sf.mTitle = title;
        sf.uri = uri;
        sf.mac = mac;
        return sf;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mClient = new BluetoothClient(getContext());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fr_simple_card, null);
        mImageView = (ImageView) v.findViewById(R.id.image);
        mTextButton = (TextView) v.findViewById(R.id.text_button);
        handtext = (TextView) v.findViewById(R.id.handtext);
        foottext = (TextView) v.findViewById(R.id.foottext);
        mLinearLayout = (LinearLayout) v.findViewById(R.id.linelayout);
        mProgressBar = (Button) v.findViewById(R.id.progressview);
        mPhone = Utils.getString(ContectUtils.PHONESAVE);
        mModleButton = (TextView) v.findViewById(R.id.modle_button);
        mStringButton = (TextView) v.findViewById(R.id.string_button);
        mModleButton.setOnClickListener(this);
        mStringButton.setOnClickListener(this);
        mProgressBar.setOnClickListener(this);
        mTextButton.setOnClickListener(this);
        if (TextUtils.equals(mTitle, "0")) {
            handtext.setVisibility(View.INVISIBLE);
            foottext.setVisibility(View.INVISIBLE);
            if (TextUtils.isEmpty(uri)) {
                mProgressBar.setVisibility(View.VISIBLE);
                mImageView.setVisibility(View.GONE);
            } else {
                mImageView.setVisibility(View.GONE);
                mLinearLayout.setVisibility(View.VISIBLE);
                if (CompontApplayCation.isStart == 1) {
                    mTextButton.setText("蓝牙连接");
                    mTextButton.setSelected(false);
                    mTextButton.setTextColor(getContext().getResources().getColor(R.color.textColor4));
                } else if (CompontApplayCation.isStart == 2) {
                    mTextButton.setText("开始按摩");
                    mTextButton.setSelected(true);
                    mTextButton.setTextColor(getContext().getResources().getColor(R.color.textColor3));
                } else {
                    mTextButton.setText("结束按摩");
                    mTextButton.setSelected(false);
                    mTextButton.setTextColor(getContext().getResources().getColor(R.color.textColor4));
                }
            }
        } else {
            mLinearLayout.setVisibility(View.INVISIBLE);
            if (TextUtils.isEmpty(uri)) {
                mProgressBar.setVisibility(View.VISIBLE);
                mImageView.setVisibility(View.GONE);
                handtext.setVisibility(View.INVISIBLE);
                foottext.setVisibility(View.INVISIBLE);
            } else {
                handtext.setVisibility(View.VISIBLE);
                foottext.setVisibility(View.VISIBLE);
                mProgressBar.setVisibility(View.GONE);
                mImageView.setVisibility(View.VISIBLE);
                System.out.println("uri=====" + uri);
                Glide.with(getActivity()).
                        load(uri).
                        asBitmap().
                        placeholder(R.mipmap.laoding).//加载中显示的图片
//                                error(R.mipmap.eeror).//加载失败时显示的图片
                into(mImageView);
            }

        }
        return v;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //按摩模式
            case R.id.modle_button:

                break;
            //按摩强度
            case R.id.string_button:

                break;
            //绑定座椅
            case R.id.progressview:
                //  mTitle未绑定的第几个座椅
                if (TextUtils.isEmpty(mPhone) && !Utils.isPhoneNO(mPhone)) {
                    Intent intent = new Intent();
                    intent.setClass(getContext(), LoginActivity.class);
                    startActivity(intent);
                } else {
                    //当状态为4的时候,说明已经绑定过了
                    if (TextUtils.equals("4", Utils.getString(ContectUtils.STATUS))) {
                        Intent intent = new Intent();
                        intent.setClass(getContext(), SaoMaActivity.class);
                        startActivity(intent);
                    } else {
                        //当状态不为4的时候,说明没有经绑定过了
                        Intent intent = new Intent();
                        intent.setClass(getContext(), BundingSetActivity.class);
                        startActivity(intent);
                    }
                }
                break;
            //连接蓝牙开始按摩
            case R.id.text_button:
                if (mBluetoothAdapter == null) {
                    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                }
                //1.设备不支持蓝牙，结束应用
                if (mBluetoothAdapter == null) {
                    ToastMake.showToast("该设备不支持蓝牙");
                    return;
                }
                //2.判断蓝牙是否打开
                //true表示已经开启，false表示蓝牙并没启用
                if (!mBluetoothAdapter.enable()) {
                    mBluetoothAdapter.enable();
                    return;
                }
                startSerch();
                break;
        }
    }


    private void startSerch() {
        SearchRequest request = new SearchRequest.Builder()
                .searchBluetoothLeDevice(3000, 3)   // 先扫BLE设备3次，每次3s
                .searchBluetoothClassicDevice(5000) // 再扫经典蓝牙5s
                .searchBluetoothLeDevice(2000)      // 再扫BLE设备2s
                .build();

        mClient.search(request, new SearchResponse() {
            @Override
            public void onSearchStarted() {

            }

            @Override
            public void onDeviceFounded(final SearchResult device) {

                if (TextUtils.equals(device.getAddress(), "FE:FE:50:DE:6E:51")) {
                    System.out.println("扫描出来了");
                    mClient.stopSearch();
                    int io=device.rssi;
                    System.out.println("io="+io);
                    int status = mClient.getConnectStatus(device.getAddress());
                    System.out.println("status="+status);
                    mClient.connect(device.getAddress(), new BleConnectResponse() {
                        @Override
                        public void onResponse(int code, BleGattProfile profile) {
                            if (code == REQUEST_SUCCESS) {
                                System.out.println("连接成功");
                                int status = mClient.getConnectStatus(device.getAddress());
                                System.out.println("status="+status);
//                                public static final int STATE_DISCONNECTED  = 0;
//                                    /** The profile is in connecting state */
//                                    public static final int STATE_CONNECTING    = 1;
//                                    /** The profile is in connected state */
//                                    public static final int STATE_CONNECTED     = 2;
//                                    /** The profile is in disconnecting state */
//                                    public static final int STATE_DISCONNECTING = 3;
                                if (status==0||status==3){
                                    System.out.println("蓝牙尚未连接");
                                }
                                if (status==1){
                                    System.out.println("蓝牙正在连接中.....");
                                }
                                if (status==2){
                                    System.out.println("蓝牙已经连接");
                                    mClient.writeNoRsp(device.getAddress(), serviceUUID, characterUUID, "5A010B62".getBytes(), new BleWriteResponse() {
                                        @Override
                                        public void onResponse(int code) {
                                            System.out.println("发送的code"+code);
                                            if (code == REQUEST_SUCCESS) {
                                                System.out.println("信息发送成功");
                                            }
                                        }
                                    });
                                    mClient.writeNoRsp(device.getAddress(), serviceUUID, characterUUID, "5A010B64".getBytes(), new BleWriteResponse() {
                                        @Override
                                        public void onResponse(int code) {
                                            System.out.println("发送的code"+code);
                                            if (code == REQUEST_SUCCESS) {
                                                System.out.println("信息发送成功");
                                            }
                                        }
                                    });

                                }
                            }

                        }
                    });
                }


            }

            @Override
            public void onSearchStopped() {

            }

            @Override
            public void onSearchCanceled() {

            }
        });
    }


}